import 'package:demo/app/widgets/CommonDialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../utils/sp_util.dart';
import '../../routes/app_pages.dart';

class DevSettingController extends GetxController {

  var isOpenProxy = false.obs;
  var isTestUrl = false.obs;
  TextEditingController hostController = TextEditingController();
  TextEditingController portController = TextEditingController();

  @override
  void onInit() {
    super.onInit();

    isOpenProxy.value = SpUtil.read(SpUtil.IS_OPEN_PROXY,false);
    hostController.text = SpUtil.read(SpUtil.PROXY_HOST,'');
    portController.text = SpUtil.read(SpUtil.PROXY_PORT,'8888');

    isTestUrl.value = SpUtil.read(SpUtil.IS_TEST_URL,false);
  }

  void save(){
    if(isOpenProxy.value){
      if(hostController.text.isEmpty){
        EasyLoading.showToast('请输入服务器');
        return;
      }
      if(portController.text.isEmpty){
        EasyLoading.showToast('请输入端口');
        return;
      }
      SpUtil.write(SpUtil.IS_OPEN_PROXY,true);
      SpUtil.write(SpUtil.PROXY_HOST,hostController.text);
      SpUtil.write(SpUtil.PROXY_PORT,portController.text);
    }else{
      SpUtil.write(SpUtil.IS_OPEN_PROXY,false);
      // SpUtil.write(SpUtil.PROXY_HOST,''); // 不清了
      // SpUtil.write(SpUtil.PROXY_PORT,'');
    }

    SpUtil.write(SpUtil.IS_TEST_URL,isTestUrl.value);


    Get.dialog(
      CommonDialog(
          hintNo: true,
          contentStr: '保存成功，需要重新打开APP生效',
          yesStr: '退出',
          yesFun: ()=> SystemNavigator.pop()
      ),
    );
  }

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  var platform = const MethodChannel("sing.top/rth");
  @override
  void onReady() {
    super.onReady();
    platform.setMethodCallHandler(flutterMethod);
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'faceOk':
        Map<dynamic, dynamic> data = methodCall.arguments; // {"dec_image":"","score":""}
        EasyLoading.showToast('完成，${data['data']}');
        break;
      case 'faceError':
        Map<dynamic, dynamic> data = methodCall.arguments; // {"err_code":1,"verify_status":1,"risk_level":1}
        Get.toNamed(Routes.FACE_ERROR,arguments: data);
        break;
      case 'loadAdOver': // 广告加载完成
        String data = methodCall.arguments as String; // {}
        EasyLoading.showToast('广告加载完成或没有广告');
        break;
      case 'scanIdCardOver': // 身份证识别结束
      // {
      //   "error_message":"错误信息，为空代表识别成功，必须有相关字段",
      //   "is_front":true,    // bool值，是否为人像面
      //   "id_number":"身份证号",
      //   "real_name":"姓名",
      //   "address":"地址",
      //   "gender":"性别",
      //   "nation":"民族",
      //   "birthday":"生日",
      //   "issued_by":"发证机关",
      //   "valid_date":"有效期，-连接",
      // }
        Map<dynamic, dynamic> data = methodCall.arguments;
        String errorMsg = data['error_message'] ?? '';
        if(errorMsg.isNotEmpty){ // 报错了
          EasyLoading.showToast(errorMsg);
          return;
        }
        bool isFront = data['is_front'] ?? true;
        var imagePath = data['image_path'] ?? '';

        if(isFront){
          Get.dialog(
            CommonDialog(
              contentStr:'isFront = $isFront，\nidNumber = ${data['id_number'] ?? ''}，\nrealName = ${data['real_name'] ?? ''}，\naddress = ${data['address'] ?? ''}，\ngender = ${data['gender'] ?? ''}，\nnation = ${data['nation'] ?? ''}，\nbirthday = ${data['birthday'] ?? ''}，\nimagePath = $imagePath',
              yesStr: '同意',
              noStr: '拒绝',
              hintNo: true,
            ),
          );
        }else{
          Get.dialog(
            CommonDialog(
              contentStr:'isFront = $isFront，\nissuedBy = ${data['issued_by'] ?? ''}，\nvalidDate = ${data['valid_date'] ?? ''}，\nimagePath = $imagePath',
              yesStr: '同意',
              noStr: '拒绝',
              hintNo: true,
            ),
          );
        }
        break;
    }
  }



  // 去人脸识别
  toFace() {
    // if(GetPlatform.isIOS){
      // // 请求权限
      // Map<Permission, PermissionStatus> statuses = await [
      //   Permission.camera,
      //   Permission.photos,
      // ].request();
      //
      // // 检查权限状态
      // PermissionStatus? locationStatus1 = statuses[Permission.camera];
      // PermissionStatus? locationStatus2 = statuses[Permission.photos];
      // if (locationStatus1 == PermissionStatus.granted && locationStatus2 == PermissionStatus.granted) {// 权限被授予
        platform.invokeMethod('toFace',{ 'name':'姓名' ,'identityNum':'身份证号'});
        // } else if (locationStatus == PermissionStatus.denied) {// 权限被拒绝
        //   EasyLoading.showToast('请开启相关权限后继续');
        // } else if (locationStatus == PermissionStatus.neverAskAgain) { // 用户选择不再提示，需引导用户去设置中开启
      // } else  {
      //   EasyLoading.showToast('请开启相关权限后继续');
      // }
    // }
  }
  // 去银行卡识别
  toBank() {
    // if(GetPlatform.isIOS){
      platform.invokeMethod('scanBank');
    // }
  }
  // 身份证扫描。isFront 头像面
  toScanIdFront(bool isFront) {
    // Android 需要初始化
    Map<String, dynamic> map = {};
    map['is_front'] = isFront;
    platform.invokeMethod('scanIdCard',map);
  }

  // 去广告
  toAd(){
    platform.invokeMethod('loadAd');
  }
}
